package com.x.share.mid.utils;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.x.share.mid.http.client.SSLHttpClient;
import com.x.share.mid.prop.WxProperties;

/**
 * 微信模板消息：<br>
 * 公众号（服务号）开通后，启用"模板消息" <br>
 * 所在行业 IT科技 互联网|电子商务，教育 培训 <br>
 * 目前直播课使用到的模板消息有：
 * 
 * <pre>
 * OPENTM400833477 上课提醒 教育 培训<br>
 * OPENTM408875752 课程完成通知 教育 培训<br>
 * </pre>
 * 
 * @author chenheng
 *
 */
public class WxTempMsgUtils {

	static Logger logger = LoggerFactory.getLogger(WxTempMsgUtils.class);

	public static String sendMessage(WxProperties props, String accessToken, WxTemplateIn in) {
		try {
			SSLHttpClient client = new SSLHttpClient(props.getCertPath(), props.getMerchantId());
			String url = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s",
					accessToken);
			String rlt = client.post(url, JSON.toJSONString(in));
			logger.info(">>>> send message result: {}", rlt);
			return rlt;
		} catch (Exception e) {
			logger.warn("!!!! exception: {}", e);
		}
		return null;
	}
	
	public static String formatDuration(Integer duration) {
		if (duration == null || duration == 0) {
			return "0分钟";
		} else {
			if (duration/60 > 0) {
				return String.format("%s小时%s分钟", duration/60, duration%60);
			}
			return String.format("%s分钟", duration);
		}
	}

	public static class WxTemplateIn {
		/**
		 * 模板消息id
		 */
		private String template_id;
		/**
		 * 用户openId
		 */
		private String touser;
		/**
		 * URL置空，则在发送后，点击模板消息会进入一个空白页面（ios），或无法点击（android）
		 */
		private String url;
		/**
		 * 标题颜色
		 */
		private String topcolor;
		/**
		 * 详细内容
		 */
		private Map<String, TData> data;

		public String getTemplate_id() {
			return template_id;
		}

		public void setTemplate_id(String template_id) {
			this.template_id = template_id;
		}

		public String getTouser() {
			return touser;
		}

		public void setTouser(String touser) {
			this.touser = touser;
		}

		public String getUrl() {
			return url;
		}

		public void setUrl(String url) {
			this.url = url;
		}

		public String getTopcolor() {
			return topcolor;
		}

		public void setTopcolor(String topcolor) {
			this.topcolor = topcolor;
		}

		public Map<String, TData> getData() {
			return data;
		}

		public void setData(Map<String, TData> data) {
			this.data = data;
		}

	}

	public static class TData {
		private String value;
		private String color;

		public TData(String value, String color) {
			this.value = value;
			this.color = color;
		}

		public String getValue() {
			return value;
		}

		public void setValue(String value) {
			this.value = value;
		}

		public String getColor() {
			return color;
		}

		public void setColor(String color) {
			this.color = color;
		}
	}
}
